const fs = require('fs')
const path = require('path')
const express = require('express')
const webpackConfig = require('../webpack.config.js')
const favicon = require('serve-favicon')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
var proxy = require('http-proxy-middleware');
const db = require('./db')
const resolve = file => path.resolve(__dirname, file)
const api = require('./api')
const app = express()

// const createBundleRenderer = require('vue-server-renderer').createBundleRenderer

app.set('port', (process.env.port || 3002))
app.use(favicon(resolve('../dist/favicon.ico')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(cookieParser())
app.use('/dist', express.static(resolve('../dist')))
// app.use(api)

var proxyTable = webpackConfig.plugins[3].options.options.proxyTable;
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxy(context, options))
})



app.post('/test',function (req,res,next) {
  console.log(req.url);
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  res.jsonp('sucess')
  res.end();
});

//设置跨域访问
app.all('*', function(req, res, next) {
  console.log(req.url);
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  const fileName = 'index.html';
  const html = fs.readFileSync(resolve('../' + fileName), 'utf-8')
  res.send(html)
  res.end();
});




app.listen(app.get('port'), function () {
  console.log('Visit http://localhost:' + app.get('port'))
})
